package com.yoomiito.app.base;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.umeng.message.PushAgent;
import com.umeng.socialize.UMShareAPI;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.net.YmApi;
import com.yoomiito.app.taobao.WebViewSqActivity;
import com.yoomiito.app.ui.welcome.SplashPagerActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AppManager;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.widget.dialog.LoadDialog;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.widget.dialog.NoNetDialog;
import com.yoomiito.app.widget.state.StatusManager;
import com.yoomiito.app.widget.TipDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.mvp.XActivity;
import cn.droidlover.xdroidmvp.net.ApiException;
import cn.droidlover.xdroidmvp.net.ApiSubscriber;
import cn.droidlover.xdroidmvp.net.XApi;

public abstract class BaseActivity<P extends BaseActPresenter> extends XActivity<P> {
    public String TAG = this.getClass().getSimpleName();
    private TextView mTvCenter;
    public StatusManager mStatusManager;
    private LoadDialog loadDialog;
    private NoNetDialog mNoNetDialog;
    boolean agreed;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            App.mAppConfig.mCurrentUser.mUserInfo = (UserInfo) savedInstanceState.getSerializable(Constant.UserInfo);
        }
        agreed = SharedPref.getInstance(this).getBoolean(Const.Common.ShowUserPermissionTip, false);
        if (agreed) {
            PushAgent.getInstance(context).onAppStart();//友盟推送统计
        }
        EventBus.getDefault().register(this);
        AppManager.getAppManager().addActivity(this);
        initTitleBar();
        //初始化沉浸式
        if (isImmersionBarEnabled()) {
            initImmersionBar();
        }

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        updateUserInfo();
    }

    public void updateUserInfo() {
        if (App.mAppConfig.getIsLogin()) {
            YmApi.getYmService()
                    .getUserInfo()
//                    .compose(bindToLifecycle())
                    .compose(XApi.<UserInfo>getApiTransformerData())
                    .compose(XApi.<UserInfo>getScheduler())
                    .subscribe(new ApiSubscriber<UserInfo>() {
                        @Override
                        public void onSuccess(UserInfo userInfo) {
                            setUserInfo(userInfo);
                            dismissLoading();
                        }

                        @Override
                        public void onFail(ApiException error) {
                            dismissLoading();
                        }
                    });
        }
    }

    //    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        outState.putSerializable(Constant.UserInfo,App.mAppConfig.mCurrentUser.mUserInfo);
//        super.onSaveInstanceState(outState);
//
//    }
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putSerializable(Constant.UserInfo, App.mAppConfig.mCurrentUser.mUserInfo);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        App.mAppConfig.mCurrentUser.mUserInfo = (UserInfo) savedInstanceState.getSerializable(Constant.UserInfo);
    }

    private void initTitleBar() {
        View titleBar = findViewById(R.id.title_layout);
        if (titleBar != null) {
            ImageView backIv = titleBar.findViewById(R.id.iv_back_left);
            mTvCenter = titleBar.findViewById(R.id.tv_center);
            backIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    public void setCenterTv(String s) {
        if (mTvCenter != null) {
            mTvCenter.setText(s);
        }
    }

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
//                .statusBarColor(initImmersionStatusBarColor()==0?R.color.colorPrimary:initImmersionStatusBarColor())
                .statusBarColor(R.color.colorPrimary)
                .statusBarDarkFont(true)
                .navigationBarColor(R.color.colorPrimary)
                .init();
    }

    public int initImmersionStatusBarColor() {
        return 0;
    }

    public void setUserInfo(UserInfo userInfo) {
        dismissLoading();
        if (userInfo == null) {
//            AllUtils.toLogin(this, AllCode.LoginIn);
            LoginUtils.INSTANCE.toOneKeyLogin(this);
            finish();
        } else {
            App.mAppConfig.mCurrentUser.mUserInfo = userInfo;
            UserInfoConfig.updateRoleId(userInfo);
            EventMessage msg = new EventMessage();
            msg.setEventType(Type.EventMsgType.UPDATE_USER_INFO);
            EventBus.getDefault().post(msg);
        }
    }

    public void showNewDialog(boolean show) {
        if (mNoNetDialog == null) {
            mNoNetDialog = new NoNetDialog(context);
        }
        if (show) {
            if (!mNoNetDialog.isShowing()) {
                mNoNetDialog.show();
            }
        } else {
            mNoNetDialog.dismiss();
        }
    }

    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    public void showToast(String str) {
        getvDelegate().toastShort(str);
    }

    public void showLongToast(String str) {
        getvDelegate().toastLong(str);
    }

    public void showCenterToastShort(String msg) {
        getvDelegate().centerToastShort(msg);
    }

    public void showCenterToastLong(String msg) {
        getvDelegate().centerToastLong(msg);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void eventMessage(EventMessage eventMessage) {
        if (AllCode.LoginOut.equals(eventMessage.getEventType())//退出登录
//                ||AllCode.LoginSuccess.equals(eventMessage.getEventType())){//登录成功
        ) {
            finish();
        }
        L.i("BaseActivity收到消息");
        if (AllCode.NET_DIALOG_SHOW.equals(eventMessage.getEventType())) {
            showNewDialog(true);
            L.i("BaseActivity收到消息：显示网络弹窗");
        }
        if (AllCode.NET_DIALOG_DISMISS.equals(eventMessage.getEventType())) {
            showNewDialog(false);
            L.i("BaseActivity收到消息：取消网络弹窗");
        }
    }

    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected boolean isImmersionBarEnabled() {
        return true;
    }

    public void showContentView() {
        if (mStatusManager != null)
            mStatusManager.showContent();
    }

    public void showEmptyView() {
        if (mStatusManager != null)
            mStatusManager.showEmpty();
    }

    public void showProgressView() {
        if (mStatusManager != null)
            mStatusManager.showProgress();
    }

    public void showErrorView() {
        if (mStatusManager != null)
            mStatusManager.showError();
    }

    public void showLoading() {
        if (loadDialog == null) {
            loadDialog = new LoadDialog(this);
        }
        loadDialog.show();
    }

    public void dismissLoading() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    @Override
    public void handleError(ApiException e) {

        switch (e.getCode()) {
//            case ApiException.UNKNOWN:
//            case ApiException.NETWORD_ERROR:
//            case ApiException.TIME_OUT_ERROR:
//            case ApiException.VERIFICATION_CODE_TYPE:
//            case ApiException.WEIXIN_BANGDING_TYPE:
//            case ApiException.INVITATION_CODE_TYPE:
//            case ApiException.INPUT_INVITATION_CODE_TYPE:
//            case ApiException.YES_INVITE_TYPE:
//            case ApiException.WEIXIN_AUTHORIZATION_TYPE:
//            case ApiException.AUTHORIZATION_DATA_TYPE:
//                showToast(e.getMsg());
//                break;
//            case 4003:
//                return;
            case ApiException.TOKEN_OUT_DATA:
//                AllUtils.toLogin(this, AllCode.LoginIn);
                LoginUtils.INSTANCE.toOneKeyLogin(this);
                finish();
                break;
            default:
                if (!TextUtils.isEmpty(e.getMsg()))
                    showToast(e.getMsg());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 在{@link WebViewSqActivity}中处理
         */
//        if (AllCode.TaoBaoAuthRequestCode == requestCode && AllCode.TaoBaoAuthResultCode == resultCode) {
//            String code = data.getStringExtra("sq_code");
//            if ("1".equals(code)) {
//                Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
//                showLoading();
//                getP().getUserInfo();
//            } else {
////                Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
//                String msg = data.getStringExtra(Constant.MSG);
//                if (TextUtils.isEmpty(msg)) {
//                    Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
//                } else {
//                    YMToast.showText(msg);
//                }
////                Log.i("YOM","SS: "+Thread.currentThread());
//                showLoading();
//                if (getP() != null)
//                    getP().getUserInfo();
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        AppManager.getAppManager().finishActivity(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        if (agreed) {
            UMShareAPI.get(this).release();
        }
        if (isImmersionBarEnabled()) {
            ImmersionBar.with(this).destroy();
        }
    }

    /**
     * 显示选择性的对话框
     *
     * @param content
     */
    public void showSelectDialog(String tipText, String content, String sureText, String cancelText, TipDialog.Dialogcallback dialogcallback) {
        TipDialog dialog = new TipDialog(context, TipDialog.TYPE_SELECT);
        dialog.setTopTipText(tipText);
        dialog.setTipText(content);
        dialog.setSureText(sureText);
        dialog.setcancleText(cancelText);
        dialog.setDialogCallback(dialogcallback);
        dialog.show();
    }

    public void showSelectDialog_1(String tipText, String tipTopText, String sureText, String cancelText, TipDialog.Dialogcallback dialogcallback) {
        TipDialog dialog = new TipDialog(context, TipDialog.TYPE_SELECT);
        dialog.setTipText(tipText);
        dialog.setTopTipText(tipTopText);
        dialog.setSureText(sureText);
        dialog.setcancleText(cancelText);
        dialog.setDialogCallback(dialogcallback);
        dialog.show();
    }

    /**
     * 显示选择性的对话框
     */
    public TipDialog showEditDialog(String topTipText, String sureText, String cancelText, TipDialog.Dialogcallback dialogcallback) {
        TipDialog dialog = new TipDialog(context, TipDialog.TYPE_EDIT);
        dialog.setTopTipText(topTipText);
        dialog.setSureText(sureText);
        dialog.setcancleText(cancelText);
        dialog.setDialogCallback(dialogcallback);
        dialog.show();
        return dialog;
    }

    /**
     * 显示选择性的对话框
     */
    public TipDialog showEditDialog(String topTipText, String etContent, String sureText, String cancelText, TipDialog.Dialogcallback dialogcallback) {
        TipDialog dialog = new TipDialog(context, TipDialog.TYPE_EDIT);
        dialog.setTopTipText(topTipText);
        dialog.setSureText(sureText);
        dialog.setcancleText(cancelText);
        L.i("name1: " + etContent);
        dialog.setEtContent(etContent);
        dialog.setDialogCallback(dialogcallback);
        dialog.show();
        return dialog;
    }
}
